package com.xxx.bluetooth;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;



/**
 * A simple {@link Fragment} subclass.
 * @author hdz
 */
public class BleServerFragment extends Fragment implements BleServerService.BleStateListener {

    private ServiceConnection mBleServeServiceConnection;
    private BleServerService.IServiceControl mBleServerServiceBinder = null;

    public BleServerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ble_server, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.bindService();
    }

    @Override
    public void onDestroy() {
        this.unbindService();
        super.onDestroy();
    }

    private void bindService() {
        mBleServeServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mBleServerServiceBinder = (BleServerService.IServiceControl)service;
                mBleServerServiceBinder.setBleStateListener(BleServerFragment.this);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mBleServerServiceBinder = null;
            }
        };
        Intent intent = new Intent(getContext(), BleServerService.class);


        getContext().bindService(intent, mBleServeServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void unbindService() {
        if (mBleServeServiceConnection != null) {
            getContext().unbindService(mBleServeServiceConnection);
            mBleServeServiceConnection = null;
        }
    }

    @Override
    public void onConnectionStateChange(final boolean bConnected, final String devName, final String devAddr) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView textView = (TextView)getView().findViewById(R.id.text);
                if (bConnected) {
                    textView.setText(""+devName+"("+devAddr+")"+"已连接");
                } else {
                    textView.setText(""+devName+"("+devAddr+")"+"已断开");
                }
            }
        });

    }
}
